package com.example.springboot.controller.tesseract;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/10/18 22:37
 */
@RestController
@RequestMapping("/tesser")
public class TessercactController {
    @PostMapping("/image/extract")
    public String reg(@RequestParam("file") MultipartFile multipartFile) throws IOException {
        String result = "";
        // 拿到原始名称
        String originalFilename = multipartFile.getOriginalFilename();
        File file = new File(System.getProperty("user.dir") + "\\" + originalFilename);
        if (!file.exists()) {
            file.createNewFile();
        }
        multipartFile.transferTo(file);
        // 瓶邪tesseract命令
        String cmd = String.format("tesseract %s stdout -l %s", System.getProperty("user.dir") + "\\" + originalFilename, "chi_sim");
        result=cmd(cmd);
        return result;
    }

    private String cmd(String cmd) {
        BufferedReader bufferedReader=null;
        try {
            // 构建执行程序
            Process process = Runtime.getRuntime().exec(cmd);
            bufferedReader=new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line=null;
            StringBuilder builder=new StringBuilder();
            while ((line=bufferedReader.readLine())!=null){
                builder.append(line);
            }
            return builder.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
